const mysql = require('mysql2/promise');
const dotenv = require('dotenv');

dotenv.config();

// 数据库配置
const dbConfig = {
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  port: process.env.DB_PORT,
  connectTimeout: parseInt(process.env.DB_CONNECT_TIMEOUT || '5000'),
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
};

// 创建连接池
const pool = mysql.createPool(dbConfig);

// 测试数据库连接
async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('✅ 数据库连接成功');
    connection.release();
    return true;
  } catch (err) {
    console.error('❌ 数据库连接失败:', err.message);
    throw err;
  }
}

module.exports = {
  pool,
  testConnection
};
